<!--
 * @Author: Wangtao
 * @Date: 2020-09-21 09:55:09
 * @LastEditors: Wangtao
 * @LastEditTime: 2020-10-17 18:08:03
-->
<template>
  <continer>
    <template slot="search">
      <QuickSearch :advForm="quickSearchForm" @QuickSearch="search"></QuickSearch>
    </template>
    <template slot="oprate">
      <el-button type="primary" size="mini" @click="search">查询</el-button>
      <el-button size="mini" @click="addVoice" v-functions="['voice_database_upload']">上传</el-button>
    </template>
    <template slot="content">
      <configTable
              :headers="tableHeaders"
              :data="tableData"
              :pagingData="pagingData"
              @pageChange="pageChange"
              @pageSizeChange="pageSizeChange"
              @checkHeadersChange="checkHeadersChange">
        <template slot="column">
          <template v-for="(item, index) in checkHeaders">
            <u-table-column
                    :show-overflow-tooltip="true"
                    :resizable="false"
                    :prop="item.prop"
                    :label="item.label"
                    :key="index"
                    :sortable="item.sortable"
                    v-if="item.show && item.prop !== 'oprate' && item.prop !== 'radio'">
            </u-table-column>
            <u-table-column
                    :label="item.label"
                    :width="84"
                    :key="index"
                    v-if="item.prop === 'radio'">
              <template slot-scope="scope">
                <AudioProgress :row="scope.row" type="common" :showListen="auditionRole" :showDowload="downloadRole && auditionRole" :url="scope.row.fileUrl" :propIsplay="scope.row.isPlay" @audioClick="restTablePlay"></AudioProgress>
              </template>
            </u-table-column>
            <u-table-column
                    :label="item.label"
                    :width="70"
                    fixed="right"
                    :key="index"
                    v-if="item.prop === 'oprate' && item.show">
              <template slot-scope="scope">
                <span @click="editVoice(scope.row)" class="oprate-span" v-functions="['voice_database_edit']">编辑</span>
                <span @click="deleteVoice(scope.row)" class="delete-span oprate-span" v-functions="['voice_database_delete']">删除</span>
              </template>
            </u-table-column>
          </template>
        </template>
      </configTable>
      <AddOrEditVoice :type="type" ref="voiceRef" @refresh="fetchData"></AddOrEditVoice>
    </template>
  </continer>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import continer from '@/common/views/configCommon/ui-modules/handle-wrapper.vue'
import configTable from '@/components/configCommon/table.vue'
import QuickSearch from '@/common/views/advancedSearch/QuickSearch.vue'
import AddOrEditVoice from './AddOrEditVoice.vue'
import { IvrModule } from '@/store/modules/config/ivr'
import AudioProgress from '@/components/audio/AudioProgress.vue'
import { checkPermission } from '@/utils/directive'
interface DrawerObj {
    type: string
    form: object
}

interface PageData {
    total: number
    limit: number
    page: number
}
@Component({
  name: 'VoiceNavigation',
  components: { continer, configTable, AddOrEditVoice, AudioProgress, QuickSearch }
})
export default class extends Vue {
  [x: string]: any
  private type: string = 'add' // 当前是添加还是编辑，用抽屉里的数据操作区分
  private auditionRole: boolean = false
  private downloadRole: boolean = false
  private pagingData: PageData = { total: 0, limit: 10, page: 1 } // 翻页相关的数据控制
  private tableHeaders: object[] = [ // 基本表头配置信息
    { label: '语音名称', prop: 'name' },
    { label: '文件名', prop: 'fileName' },
    { label: '说明', prop: 'description' },
    { label: '最后更新时间', prop: 'updateTime', sortable: true },
    { label: '最后操作人', prop: 'agentName' },
    { label: '语音文件', prop: 'radio' },
    { label: '操作', prop: 'oprate' }
  ]

  private quickSearchForm = {
    form: {
      name: ''
    },
    advSearchOptions: [ // 快捷检索的数据(语音文件名称)
      { label: '语音文件名称', inputType: 'input', placeholder: '请输入语音文件名称', name: 'name', clearable: true }
    ]
  }

  private checkHeaders: [] = [] // 当前展示的表头

  private tableData: object[] = [] // table展示的数据

  private addVoice () { // 添加录音
    (this as any).$refs.voiceRef.openOrCloseDrawer()
    this.type = 'add'
  }

  private editVoice (row: any) { // 编辑录音
    (this as any).$refs.voiceRef.openOrCloseDrawer(row)
    this.type = 'edit'
  }

  private search () { // 点击查询
    this.pagingData.page = 1
    this.fetchData(null)
  }

  private pageChange (page) { // 翻页
    this.pagingData.page = page
    this.fetchData(null)
  }

  private pageSizeChange (size) { // 每页多少条数据
    this.pagingData.limit = size
    this.pagingData.page = 1
    this.fetchData(null)
  }

  private restTablePlay (id: string, currentPlay: boolean) { // 点击列表的听取录音，重置其他数据
    this.tableData.forEach((item: any) => {
      if (item._id === id) {
        item.isPlay = currentPlay
      } else {
        item.isPlay = false
      }
    })
  }

  private deleteVoice (row: any) { // 删除录音
    this.$confirm(`确定删除【${row.name}】吗`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      const data = { url: '/call/action/ivr/voiceLibrary/delete', method: 'POST', data: { _id: row._id } }
      IvrModule.IvrCommonAction(data).then((res: any) => {
        if (res && res.success) {
          this.$message({ message: `删除【${row.name}】成功！`, type: 'success' })
          this.fetchData(null)
          this.$deleteCache('voiceLibraryList', '_id', row._id, false)
        }
      })
    }).catch(e => {
      console.log(e)
    })
  }

  private checkHeadersChange (checkList) { // 设置当前展示的表头信息
    this.$set(this, 'checkHeaders', checkList)
  }

  private fetchData (addSuccess) { // 查列表
    if (addSuccess) { // 新增回到第一页
      this.pagingData.page = 1
    }
    const actionData = Object.assign({ limit: this.pagingData.limit, page: this.pagingData.page }, this.quickSearchForm.form)
    const data = { url: '/call/action/ivr/voiceLibrary/query', method: 'POST', data: actionData }
    IvrModule.IvrCommonAction(data).then((res: any) => {
      if (res && res.success) {
        const list = res.list || []
        if (list.length === 0) {
          const page = Math.ceil(res.count / this.pagingData.limit)
          if (!res.count) { // 第一页且count为0是不再发请求（!res.count，以防后端没有返回count,直接死循环）
            this.pagingData.page = 1
          } else { // 删除到最后一个回到上一页
            this.pagingData.page = page
            this.fetchData(null)
            return false
          }
        }
        list.forEach((item: any) => {
          const agentObj = this.$store.state.common.publicCache.userListObj[item.updateUser]
          item.agentName = agentObj ? agentObj.name : '--'
          item.isPlay = false
        })
        this.tableData = list
        this.pagingData.total = res.count || 0
        this.$bus.$emit('restAudioStatus') // 查询的时候，把当前启动的录音重置
      }
    })
  }

  private beforeMount () {
    this.fetchData(null)
    this.auditionRole = checkPermission(null, { value: ['voice_database_audition'] }) // 听取录音权限
    this.downloadRole = checkPermission(null, { value: ['voice_database_download'] }) // 下载录音
  }
}
</script>

<style lang="stylus" scoped>
  .oprate-span,.radio-span
    cursor pointer
    color $c-main
  .delete-span
    color $c-danger
    padding-left 10px
  .radio-span
    width 24px
    height 24px
    display inline-block
    background #fff
    margin 2px 0px 2px 0
    box-shadow 0px 1px 3px 0px rgba(216, 222, 230, 0.9)
    border-radius 50%
    font-size 12px
    color $c-main
    text-align center
    vertical-align middle
    &:last-child
     margin-right 0
     margin-left 10px
</style>
